/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 UJF.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.sensor.discovery;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.Factory;

/**
 * TODO 
 */
public class NodeDiscovery {

    private static final String MULTICAST_ALL_NODES = "FF02::1";
    
    private static final int PORT = 80;

    /**
     * SensorNode Proxy Factory, injected by iPOJO.
     */
    private Factory factory;

    private Map<String, ComponentInstance> proxies;

    // The availables network interface
    List<NetworkInterface> nics;

    private void start() {
        nics = getNetworkInterfaces();
    }

    private void stop() {
        // Destroy all proxy created through this discovery.
        for (Iterator iterator = proxies.entrySet().iterator(); iterator.hasNext();) {
            Entry<String, ComponentInstance> entry = (Entry<String, ComponentInstance>) iterator.next();
            try {
                entry.getValue().dispose();
            } catch (Exception e) {
                // TODO log
            }
            iterator.remove();
        }

    }

    /**
     * Get the available network interface.
     * @return NetworkInterface
     */
    private static List<NetworkInterface> getNetworkInterfaces() {
        List<NetworkInterface> nics = new ArrayList<NetworkInterface>();
        try {

            for (NetworkInterface nic : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                if (!nic.isLoopback() && nic.supportsMulticast()) {
                    nics.add(nic);
                }
            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return nics;
    }
}
